/*

 */
package com.joysuch.wwyt.bp.service.impl;


import cn.hutool.http.HttpRequest;
import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.joysuch.wwyt.bp.bean.BpBaseUserBean;
import com.joysuch.wwyt.bp.bean.DelayCorrectionReq;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpInspection;
import com.joysuch.wwyt.bp.entity.BpInspectionDict;
import com.joysuch.wwyt.bp.entity.vo.BpInspectionVo;
import com.joysuch.wwyt.bp.mapper.BpInspectionMapper;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.service.IBpInspectionService;
import com.joysuch.wwyt.core.bean.BaseTypeGroupItemBean;
import com.joysuch.wwyt.core.bean.BpUserListBean;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.common.util.JsonUtil;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.service.BaseTypeGroupItemService;
import com.joysuch.wwyt.core.service.BaseUserService;
import com.joysuch.wwyt.core.service.impl.BaseRoleDataAuthServiceImpl;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.util.CachedGroovyScriptEngineUtil;
import com.joysuch.wwyt.util.SpringBeanUtils;
import com.joysuch.wwyt.workflow.repository.WorkFlowTaskDao;
import com.joysuch.wwyt.workflow.service.impl.WorkFlowProcessServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 服务实现类
 */
@Slf4j
@Service
@Transactional
public class BpInspectionServiceImpl extends ServiceImpl<BpInspectionMapper, BpInspection> implements IBpInspectionService {

    @Autowired
    BpInspectionMapper bpInspectionMapper;

    @Autowired
    BpDepartDao deptDao;

    @Autowired
    BpInspectionDictServiceImpl bpInspectionDictService;

    @Autowired
    BpDepartServiceImpl bpDepartService;

    @Autowired
    BaseRoleDataAuthServiceImpl baseRoleDataAuthService;

    @Autowired
    WorkFlowProcessServiceImpl workFlowProcessService;

    @Autowired
    WorkFlowTaskDao workFlowTaskDao;
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private RiskDistrictDao riskDistrictDao;
    @Resource
    private BaseConfigService baseConfigService;
    @Resource
    private BaseTypeGroupItemService baseTypeGroupItemService;
    @Autowired
    private BaseUserDao baseUserDao;

    /**
     * 保存更新
     *
     * @param bpInspectionVo
     * @return
     */
    @Override
    public BpInspection saveOrUpdate(BpInspectionVo bpInspectionVo) {
        fillNameFields(bpInspectionVo);
        BpInspection bpInspection = new BpInspection();
        SpringBeanUtils.copyProperties(bpInspectionVo, bpInspection, false);

        /*if (bpInspectionVo.getDangerCorrectionPersonIdList() != null && bpInspectionVo.getDangerCorrectionPersonIdList().size() > 0) {
            List<Long> dangerCorrectionPersonIdList = bpInspectionVo.getDangerCorrectionPersonIdList();
            String dangerCorrectionPersonId = JSONArray.toJSONString(dangerCorrectionPersonIdList);
            bpInspection.setDangerCorrectionPersonId(dangerCorrectionPersonId);
        }*/
        if (bpInspectionVo.getDangerCorrectionPersonList() != null && bpInspectionVo.getDangerCorrectionPersonList().size() > 0) {
            List<BpBaseUserBean> dangerCorrectionPersonList = bpInspectionVo.getDangerCorrectionPersonList();
            List<Long> dangerCorrectionPersonIdList = new ArrayList<>();
            if (dangerCorrectionPersonList != null && dangerCorrectionPersonList.size() > 0) {
                for (BpBaseUserBean bpBaseUserBean : dangerCorrectionPersonList) {
                    dangerCorrectionPersonIdList.add(bpBaseUserBean.getId());
                }
            }
            String dangerCorrectionPersonId = JSONArray.toJSONString(dangerCorrectionPersonIdList);
            bpInspection.setDangerCorrectionPersonId(dangerCorrectionPersonId);
        }

        //获取部门code
        Long deptId = bpInspection.getCreateDeptId();
        String deptCode = deptDao.getOne(deptId).getCode();
        if (deptCode != null) {
            bpInspection.setCreateDeptCode(deptCode);
        }

        this.saveOrUpdate(bpInspection);

        Long id = bpInspection.getId();
        List<BpInspectionDict> list = bpInspectionVo.getBpInspectionDicts();
        list.stream().forEach(item -> item.setInspectionId(id));
        if (list.size() > 0) {
            bpInspectionDictService.saveOrUpdateBatch(list);
        }

        // 隐患
        if (bpInspection.getIsHiddenDanger() == 1) {
            BaseConfig codeConfig = baseConfigService.findConfig("quanyuanducha.starthiddendanger.code");
            if (codeConfig != null && !Strings.isNullOrEmpty(codeConfig.getValue())) {
                try {
                    String logStr = CachedGroovyScriptEngineUtil.runScript(codeConfig.getValue(), null, "execute", bpInspection);
                    log.info("全员督察创建隐患：{}", logStr);
                } catch (Exception e) {
                    log.error("生成隐患实例失败！", e);
                    throw new RuntimeException("插入隐患库失败，请联系技术人员解决");
                }
            }
        }

        return bpInspection;
    }

    private void fillNameFields(BpInspectionVo vo) {
        if (vo.getCorrectionDepartId() != null && vo.getCorrectionDepartId() > 0) {
            BpDepart depart = bpDepartService.findById(vo.getCorrectionDepartId());
            if (depart != null) {
                vo.setCorrectionDepartName(depart.getName());
            }
        }
        /*if (vo.getDangerCorrectionPersonId() != null && vo.getDangerCorrectionPersonId() > 0) {
            BpUserListBean user = baseUserService.findById(vo.getDangerCorrectionPersonId());
            if (user != null) {
                vo.setDangerCorrectionPersonName(user.getRealName());
            }
        }*/
        /*if (vo.getDangerCorrectionPersonIdList() != null) {
            List<Long> list = vo.getDangerCorrectionPersonIdList();
            if (list != null && list.size() > 0) {
                List<String> nameList = new ArrayList<>();
                for (Long aLong : list) {
                    BpUserListBean user = baseUserService.findById(aLong);
                    if (user != null) {
                        nameList.add(user.getRealName());
                    }
                }
                vo.setDangerCorrectionPersonName(JSONArray.toJSONString(nameList));
            }
        }*/
        if (vo.getDangerCorrectionPersonList() != null) {
            List<BpBaseUserBean> list = vo.getDangerCorrectionPersonList();
            if (list != null && list.size() > 0) {
                List<String> nameList = new ArrayList<>();
                for (BpBaseUserBean bpBaseUserBean : list) {
                    nameList.add(bpBaseUserBean.getName());
                }
                vo.setDangerCorrectionPersonName(JSONArray.toJSONString(nameList));
            }
        }

        if (vo.getDangerDistrictId() != null && vo.getDangerDistrictId() > 0) {
            String districtName = riskDistrictDao.getNameById(vo.getDangerDistrictId());
            if (!Strings.isNullOrEmpty(districtName)) {
                vo.setDangerDistrictName(districtName);
            }
        }
    }

    @Override
    public List<BpInspection> listPage(Integer page, Integer pageSize) {
        IPage<BpInspection> bpInspectionIPage = bpInspectionMapper.selectPage(new Page<BpInspection>(page + 1, pageSize), null);
        return bpInspectionIPage.getRecords();
    }

    /**
     * 全员督查列表
     *
     * @param params
     * @return
     */
    @Override
    public List<BpInspectionVo> listPageCondition(Map<String, String> params) {
        Integer page = StringUtils.isNotBlank(params.get("page")) ? Integer.valueOf(params.get("page")) : null;
        Integer pageSize = StringUtils.isNotBlank(params.get("size")) ? Integer.valueOf(params.get("size")) : null;
        String startTime = StringUtils.isNotBlank(params.get("startTime")) ? params.get("startTime") : null;
        String endTime = StringUtils.isNotBlank(params.get("endTime")) ? params.get("endTime") : null;
        String createUserName = StringUtils.isNotBlank(params.get("createUserName")) ? params.get("createUserName") : null;
        Long departId = StringUtils.isNotBlank(params.get("departId")) ? Long.valueOf(params.get("departId")) : null;
        Integer isContractor = StringUtils.isNotBlank(params.get("isContractor")) ? Integer.valueOf(params.get("isContractor")) : null;
        Integer isDanger = StringUtils.isNotBlank(params.get("isDanger")) ? Integer.valueOf(params.get("isDanger")) : null;
        Integer isStop = StringUtils.isNotBlank(params.get("isStop")) ? Integer.valueOf(params.get("isStop")) : null;
        Integer isHiddenDanger = StringUtils.isNotBlank(params.get("isHiddenDanger")) ? Integer.valueOf(params.get("isHiddenDanger")) : null;
        Integer contractorName = StringUtils.isNotBlank(params.get("contractorName")) ? Integer.valueOf(params.get("contractorName")) : null;

        LambdaQueryWrapper<BpInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(startTime != null, BpInspection::getCheckDate, startTime)
                .le(endTime != null, BpInspection::getCheckDate, endTime)
                .like(createUserName != null, BpInspection::getCreateUserName, createUserName)
                .eq(departId != null, BpInspection::getCreateDeptId, departId)
                .eq(isContractor != null, BpInspection::getIsContractor, isContractor)
                .eq(isDanger != null, BpInspection::getIsDanger, isDanger)
                .eq(isStop != null, BpInspection::getIsStop, isStop)
                .eq(isHiddenDanger != null, BpInspection::getIsHiddenDanger, isHiddenDanger)
                .eq(contractorName != null, BpInspection::getContractorId, contractorName)
                .eq(BpInspection::getDeleteFlag, '0');

        //数据权限
        Map<String, List<String>> authDepartCodesByCurUser = baseRoleDataAuthService.findAuthDepartCodesByCurUser();
        List<String> noChild = authDepartCodesByCurUser.get("noChild");
        List<String> hasChild = authDepartCodesByCurUser.get("hasChild");
        Set<Long> roleDataEmpByCurUser = baseRoleDataAuthService.findRoleDataEmpByCurUser();

        boolean isSuperAdmin = Context.getCurrentUser().isSuperAdmin();
        if (!isSuperAdmin) {
            if (CollectionUtils.isNotEmpty(hasChild) || CollectionUtils.isNotEmpty(noChild) || CollectionUtils.isNotEmpty(roleDataEmpByCurUser)) {
                wrapper.and(wo -> {
                    //部门
                    wo.nested(w -> {
                        if (CollectionUtils.isNotEmpty(hasChild)) {
                            for (int i = 0; i < hasChild.size(); i++) {
                                w.likeRight(BpInspection::getCreateDeptCode, hasChild.get(i));
                                if (i != hasChild.size() - 1) {
                                    w.or();
                                }
                            }
                        }
                        if (CollectionUtils.isNotEmpty(noChild)) {
                            w.or();
                            w.in(BpInspection::getCreateDeptCode, noChild);
                        }
                        return w;
                    });
                    //人员
                    if (CollectionUtils.isNotEmpty(roleDataEmpByCurUser)) {
                        wo.or();
                        wo.in(BpInspection::getCreateUserId, roleDataEmpByCurUser);
                    }
                    return wo;
                });
            }
        }

        wrapper.orderByDesc(BpInspection::getCreateTime);
        IPage<BpInspection> bpInspectionIPage = bpInspectionMapper.selectPage(new Page<BpInspection>(page + 1, pageSize), wrapper);

        List<BpInspectionVo> bpInspectionVoList = bpInspectionIPage.getRecords().stream().map(r -> {
            BpInspectionVo bpInspectionVo = new BpInspectionVo();
            SpringBeanUtils.copyProperties(r, bpInspectionVo, false);
            String dangerCorrectionPersonId = r.getDangerCorrectionPersonId();
            if (dangerCorrectionPersonId != null) {
                dangerCorrectionPersonId = dangerCorrectionPersonId.startsWith("[") ? dangerCorrectionPersonId : "[" + dangerCorrectionPersonId;
                dangerCorrectionPersonId = dangerCorrectionPersonId.endsWith("]") ? dangerCorrectionPersonId : dangerCorrectionPersonId + "]";
                List<Long> list = JSONArray.parseArray(dangerCorrectionPersonId, Long.class);
//                bpInspectionVo.setDangerCorrectionPersonIdList(list);
                List<BpBaseUserBean> bpBaseUserBeanList = new ArrayList<>();
                if (list != null && list.size() > 0) {
                    for (Long aLong : list) {
                        BpBaseUserBean bpBaseUserBean = new BpBaseUserBean();
                        if (baseUserDao.findById(aLong).isPresent()) {
                            bpBaseUserBean.setId(aLong);
                            bpBaseUserBean.setName(baseUserDao.findById(aLong).get().getRealName());
                            bpBaseUserBeanList.add(bpBaseUserBean);
                        }
                    }
                    bpInspectionVo.setDangerCorrectionPersonList(bpBaseUserBeanList);
                }
            }
            return bpInspectionVo;
        }).collect(Collectors.toList());
        return bpInspectionVoList;

//        return bpInspectionIPage.getRecords();
    }

    /**
     * 删除
     *
     * @param id
     */

    @Override
    public void deleteInspectionById(Long id) {
        BpInspection bpInspection = bpInspectionMapper.selectById(id);
        if (bpInspection == null) {
            return;
        }

        LambdaUpdateWrapper<BpInspection> wrapper = new LambdaUpdateWrapper();
        wrapper.eq(BpInspection::getId, id);
        wrapper.set(BpInspection::getDeleteFlag, '1');
        bpInspectionMapper.update(null, wrapper);

        LambdaUpdateWrapper<BpInspectionDict> wrapper_dict = new LambdaUpdateWrapper();
        wrapper_dict.eq(BpInspectionDict::getId, id);
        wrapper_dict.set(BpInspectionDict::getDeleteFlag, '1');
        bpInspectionDictService.update(wrapper_dict);

        if (!Strings.isNullOrEmpty(bpInspection.getHiddenDangerWfid())) {
            BaseConfig codeConfig = baseConfigService.findConfig("quanyuanducha.deletehiddendanger.code");
            if (codeConfig != null && !Strings.isNullOrEmpty(codeConfig.getValue())) {
                try {
                    String logStr = CachedGroovyScriptEngineUtil.runScript(codeConfig.getValue(), null, "execute", bpInspection);
                    log.info("全员督察删除隐患：{}", logStr);
                } catch (Exception e) {
                    log.error("全员督察删除实例失败！", e);
                    throw new RuntimeException("全员督察删除实例失败，请联系技术人员解决");
                }
            }
        }
    }

    @Override
    public HSSFWorkbook export(Map<String, String> params) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = sheet.createRow(0);
        setCellValue(row, 0, "提交时间");
        setCellValue(row, 1, "检查人姓名");
        setCellValue(row, 2, "检查日期");
        setCellValue(row, 3, "检查人所在部门");
        setCellValue(row, 4, "发现隐患或问题");
        setCellValue(row, 5, "整改措施或建议");
        setCellValue(row, 6, "隐患来源");
        setCellValue(row, 7, "后果级别（C）");
        setCellValue(row, 8, "频率级别（F）");
        setCellValue(row, 9, "隐患等级");
        setCellValue(row, 10, "隐患类型");
        setCellValue(row, 11, "整改部门");
        setCellValue(row, 12, "整改状态");
        setCellValue(row, 13, "计划整改日期");
        setCellValue(row, 14, "整改负责人");
        setCellValue(row, 15, "整改确认人");
        setCellValue(row, 16, "整改完成日期");
        setCellValue(row, 17, "重大危险源检查内容序号");
        setCellValue(row, 18, "重大危险源区域");
        setCellValue(row, 19, "是否发现问题或隐患");
        setCellValue(row, 20, "是否涉及承包商及考核");
        setCellValue(row, 21, "金额");
        setCellValue(row, 22, "承包商单位名称");
        setCellValue(row, 23, "是否进行了STOP");
        setCellValue(row, 24, "人员的反应");
        setCellValue(row, 25, "个人防护装备");
        setCellValue(row, 26, "人员的位置");
        setCellValue(row, 27, "工具与设备");
        setCellValue(row, 28, "程序与现场整理");
        setCellValue(row, 29, "安全的行为");
        setCellValue(row, 30, "是否进行了高危作业审核");
        setCellValue(row, 31, "高危审核内容");

        List<BaseTypeGroupItemBean> allItemList = Lists.newArrayList();
        List<BaseTypeGroupItemBean> checkItemList = baseTypeGroupItemService.findAllByTypeName("高危作业审核");
        final AtomicInteger cellNum = new AtomicInteger(32);
        checkItemList.forEach(checkItem -> {
            List<BaseTypeGroupItemBean> subItems = baseTypeGroupItemService.findAllByTypeName(checkItem.getName());
            subItems.forEach(subItem -> {
                allItemList.add(subItem);
            });
        });
        for (int i = 0; i < allItemList.size(); i++) {
            setCellValue(row, cellNum.get(), allItemList.get(i).getName());
            cellNum.incrementAndGet();
        }
        params.put("page", "0");
        params.put("size", "100000");
        List<BpInspectionVo> bpInspections = listPageCondition(params);

        int size = bpInspections.size();
        for (int i = 0; i < size; i++) {
            BpInspection bpInspection = bpInspections.get(i);

            HSSFRow sheetRow = sheet.createRow(i + 1);
            int cellNumTemp = 0;
            // 提交日期
            setCellValue(sheetRow, cellNumTemp++, DateTimeUtil.formatDate(bpInspection.getCreateTime()));
            //检查人姓名
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getCreateUserName());
            // 检查日期
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getCheckDate() == null ? "" : bpInspection.getCheckDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getCreateDeptName());
            // 发现隐患或问题
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsHiddenDanger() == null ? "" : (bpInspection.getIsHiddenDanger() == 1 ? "是" : "否"));
            //整改措施或建议
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerSuggestion() == null ? "" : bpInspection.getDangerSuggestion());
            // 隐患来源
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerSource() == null ? "" : bpInspection.getDangerSource());
            // 后果级别（C）
            setCellValue(sheetRow, cellNumTemp++, getDangerConsequence(bpInspection.getDangerConsequence()));
            // 频率级别（F）
            setCellValue(sheetRow, cellNumTemp++, getDangerFrequency(bpInspection.getDangerFrequency()));
            // 隐患等级
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerLevel() == null ? "" : bpInspection.getDangerLevel() + "");
            // 隐患类型
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerType() == null ? "" : bpInspection.getDangerType() + "");
            // 整改部门 c
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getCorrectionDepartName() == null ? "" : bpInspection.getCorrectionDepartName() + "");
            // 整改状态 hiddenDangerStatus
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsHiddenDanger() == null ? "" : (bpInspection.getIsHiddenDanger() == 1 ? "已整改" : "未整改"));
            // 计划整改日期 dangerRequireDate
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerRequireDate() == null ? "" : bpInspection.getDangerRequireDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            // 整改负责人 dangerCorrectionPersonName
            // todo 需要修改
            String dangerCorrectionPersonName = "";
            if (StringUtils.isNotEmpty(bpInspection.getDangerCorrectionPersonName())) {
                if (bpInspection.getDangerCorrectionPersonName().contains("[")) {
                    List<String> list = JsonUtil.fromListJson(bpInspection.getDangerCorrectionPersonName(), String.class);
                    dangerCorrectionPersonName = list.stream().collect(Collectors.joining(","));
                } else {
                    dangerCorrectionPersonName = bpInspection.getDangerCorrectionPersonName();
                }
            }
            setCellValue(sheetRow, cellNumTemp++, dangerCorrectionPersonName);
            // 整改确认人
            // todo 暂跟责任人一样
            setCellValue(sheetRow, cellNumTemp++, dangerCorrectionPersonName);
            // 整改完成日期
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerFinishDate() == null ? "" : bpInspection.getDangerFinishDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            // 重大危险源检查内容序号
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getMajorDangerSourceCode() == null ? "" : bpInspection.getMajorDangerSourceCode());
            // 重大危险源区域 dangerDistrictName
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getDangerDistrictName() == null ? "" : bpInspection.getDangerDistrictName() + "");
            //是否发现问题或隐患
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsHiddenDanger() == null ? "" : (bpInspection.getIsHiddenDanger() == 1 ? "是" : "否"));
            // 是否涉及承包商及考核
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsContractor() == null ? "" : (bpInspection.getIsContractor() == 1 ? "是" : "否"));
            // 金额
            setCellValue(sheetRow, cellNumTemp++, "");
            // 承包商单位名称
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getContractorName() == null ? "" : bpInspection.getContractorName() + "");
            // 是否进行了STOP
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsStop() == null ? "" : (bpInspection.getIsStop() == 1 ? "是" : "否"));
            // 人员的反应
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getReaction() == null ? "" : bpInspection.getReaction() + "");
            // 个人防护装备
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getProtect() == null ? "" : bpInspection.getProtect() + "");
            // 人员的位置
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getPersonLocation() == null ? "" : bpInspection.getPersonLocation() + "");
            // 工具与设备
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getTools() == null ? "" : bpInspection.getTools() + "");
            // 程序与现场整理
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getApp() == null ? "" : bpInspection.getApp() + "");
            // 安全的行为
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getSecurityAction() == null ? "" : bpInspection.getSecurityAction() + "");
            // 是否进行了高危作业审核
            setCellValue(sheetRow, cellNumTemp++, bpInspection.getIsDanger() == null ? "" : (bpInspection.getIsDanger() == 1 ? "是" : "否"));

            List<BpInspectionDict> inspectionDicts = bpInspectionDictService.list(new LambdaQueryWrapper<BpInspectionDict>()
                    .eq(BpInspectionDict::getInspectionId, bpInspection.getId())
                    .eq(BpInspectionDict::getDeleteFlag, "0"));

            Map<String, BpInspectionDict> inspectionDictMap = inspectionDicts.stream().collect(Collectors.toMap(BpInspectionDict::getTypeItemName, e -> e, (k1, k2) -> k2));
            // 高危审核内容
            if (!org.springframework.util.CollectionUtils.isEmpty(inspectionDicts)) {
                String typeGroupName = inspectionDicts.get(0).getTypeGroupName();
                setCellValue(sheetRow, cellNumTemp++, typeGroupName == null ? "" : typeGroupName + "");
            } else {
                setCellValue(sheetRow, cellNumTemp++, "");
            }
            for (BaseTypeGroupItemBean bean : allItemList) {
                BpInspectionDict bpInspectionDict = inspectionDictMap.get(bean.getName());
                String score = "";
                if (bpInspectionDict != null && bpInspectionDict.getScore() != null) {
                    score = bpInspectionDict.getScore() + "";
                }
                setCellValue(sheetRow, cellNumTemp++, score);
            }

        }

        return workbook;
    }

    @Override
    public void delayCorrection(DelayCorrectionReq req) {
        BpInspection ins = this.getById(req.getId());
        if (ins.getHiddenDangerStatus() != null && ins.getHiddenDangerStatus() == 1) {
            throw new RuntimeException("该隐患已经被整改，无需延期整改");
        }
        String wfid = ins.getHiddenDangerWfid();
        if (Strings.isNullOrEmpty(wfid)) {
            throw new RuntimeException("该隐患没有找到对应的整改流程");
        }

        String requireLabel = "要求整改时间";
        BaseConfig requireDateLabel = baseConfigService.findConfig("quanyuanducha.require.data.label");
        if (requireDateLabel != null && !Strings.isNullOrEmpty(requireDateLabel.getValue())) {
            requireLabel = requireDateLabel.getValue();
        }

        Map<String, Object> param = new HashMap<>();
        param.put("processInsId", wfid);
        Map<String, String> variables = new HashMap<>();
        variables.put(requireLabel, req.getDangerRequireDate());
        param.put("variables", variables);
        String body = JsonUtil.toJson(param);

        String appid = "mvAmIwYJ7x6y0EADQvUb";
        String signature = "30ca19ac3d133b30b9243ed61646136f7818a3d85e6a70a3bfaa68d3d64566c3";
        String wfUrl = "http://127.0.0.1:8886";
        BaseConfig wfAddr = baseConfigService.findConfig("workflow.ip.address");
        if (wfAddr != null && !Strings.isNullOrEmpty(wfAddr.getValue())) {
            wfUrl = wfAddr.getValue();
        }
        Long tenantId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        Long userId = Context.getCurrentUserId();
        String userName = Context.getCurrentUser().getUsername();
        String updateRes = HttpRequest.post(wfUrl + "/api/blade-workflow/process/update-task-variables")
                .header("app-id", appid)
                .header("signature", signature)
                .header("tenant-id", tenantId.toString())
                .header("org-code", orgCode)
                .header("user-id", userId.toString())
                .header("user-name", userName)
                .body(body)
                .timeout(10000)
                .execute()
                .body();
        JsonObject updateResObj = new JsonParser().parse(updateRes).getAsJsonObject();
        if (!updateResObj.get("success").getAsBoolean()) {
            throw new RuntimeException("全员督查更新隐患整改日期失败，请联系技术人员解决");
        }

        LambdaUpdateWrapper<BpInspection> u = new LambdaUpdateWrapper<>();
        u.set(BpInspection::getDangerRequireDate, LocalDate.parse(req.getDangerRequireDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        u.eq(BpInspection::getId, req.getId());
        this.update(u);
    }

    private String getDangerFrequency(Integer dangerFrequency) {
        if (dangerFrequency == null) {
            return "";
        }
        if (dangerFrequency.intValue() == 1) {
            return "F-1极不可能";
        }
        if (dangerFrequency.intValue() == 2) {
            return "F-2一般不可能";
        }
        if (dangerFrequency.intValue() == 3) {
            return "F-3可能";
        }
        if (dangerFrequency.intValue() == 4) {
            return "F-4很可能";
        }
        return "";
    }

    private String getDangerConsequence(Integer dangerConsequence) {
        if (dangerConsequence == null) {
            return "";
        }
        if (dangerConsequence.intValue() == 1) {
            return "C-1轻微";
        }
        if (dangerConsequence.intValue() == 2) {
            return "C-2中等";
        }
        if (dangerConsequence.intValue() == 3) {
            return "C-3较严重";
        }
        if (dangerConsequence.intValue() == 4) {
            return "C-4灾难性";
        }
        return "";
    }


    private void setCellValue(HSSFRow row, int i, String value) {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(value);
    }


    /**
     * ID查询
     *
     * @param inspectionId
     * @return
     */

    @Override
    public BpInspectionVo getInspectionById(Long inspectionId) {
        LambdaQueryWrapper<BpInspection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BpInspection::getId, inspectionId);
        BpInspection bpInspection = bpInspectionMapper.selectOne(wrapper);

        LambdaQueryWrapper<BpInspectionDict> wrapper_dict = new LambdaQueryWrapper<>();
        wrapper_dict.eq(BpInspectionDict::getInspectionId, inspectionId);
        List<BpInspectionDict> bpInspectionDicts = bpInspectionDictService.getBaseMapper().selectList(wrapper_dict);

        BpInspectionVo bpInspectionVo = new BpInspectionVo();

        SpringBeanUtils.copyProperties(bpInspection, bpInspectionVo, false);
        bpInspectionVo.setBpInspectionDicts(bpInspectionDicts);

        String dangerCorrectionPersonId = bpInspection.getDangerCorrectionPersonId();
        if (dangerCorrectionPersonId != null) {
            dangerCorrectionPersonId = dangerCorrectionPersonId.startsWith("[") ? dangerCorrectionPersonId : "[" + dangerCorrectionPersonId;
            dangerCorrectionPersonId = dangerCorrectionPersonId.endsWith("]") ? dangerCorrectionPersonId : dangerCorrectionPersonId + "]";
            List<Long> list = JSONArray.parseArray(dangerCorrectionPersonId, Long.class);
//                bpInspectionVo.setDangerCorrectionPersonIdList(list);
            List<BpBaseUserBean> bpBaseUserBeanList = new ArrayList<>();
            if (list != null && list.size() > 0) {
                for (Long aLong : list) {
                    BpBaseUserBean bpBaseUserBean = new BpBaseUserBean();
                    if (baseUserDao.findById(aLong).isPresent()) {
                        bpBaseUserBean.setId(aLong);
                        bpBaseUserBean.setName(baseUserDao.findById(aLong).get().getRealName());
                        bpBaseUserBeanList.add(bpBaseUserBean);
                    }
                }
                bpInspectionVo.setDangerCorrectionPersonList(bpBaseUserBeanList);
            }
        }

        return bpInspectionVo;
    }


}
